import 'dart:typed_data';
import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:fluwx/fluwx.dart';
import 'package:provider/provider.dart';
import 'package:qr_flutter/qr_flutter.dart';
import 'package:tender_flutter/constant/api_path.dart';
import 'package:tender_flutter/constant/resource_path.dart';
import 'package:tender_flutter/constant/theme_colors.dart';
import 'package:tender_flutter/dialog/share_bottom_sheet.dart';
import 'package:tender_flutter/http/api_response.dart';
import 'package:tender_flutter/page/person/api/api_person.dart';
import 'package:tender_flutter/page/person/model/poster_entity.dart';
import 'package:tender_flutter/providers/user_profile.dart';
import 'package:tender_flutter/router/router.dart';
import 'package:tender_flutter/router/router_map.gr.dart';
import 'package:tender_flutter/style/font_style.dart';
import 'package:tender_flutter/utils/screen_adaper.dart';
import 'package:tender_flutter/utils/share.dart';
import 'package:tender_flutter/utils/toast.dart';
import 'package:tender_flutter/widgets/base_appbar.dart';
import 'package:tender_flutter/widgets/net_image.dart';

class InviatePage extends StatefulWidget {
  @override
  _InviatePageState createState() => _InviatePageState();
}

class _InviatePageState extends State<InviatePage> {
  /// 邀请码
  String inviteCode;

  /// pageView控制器
  PageController pageController;

  /// pageView当前显示的索引
  int currentPage = 0;

  List<PosterEntity> _listDatas;

  /// 获取海报图片
  Future<ApiResponse<List<PosterEntity>>> _getList() async {
    var response = await ApiPerson.getInvitePoster<List<PosterEntity>>();
    _listDatas = response.result;
    for (PosterEntity entity in _listDatas) {
      entity.globalKey = new GlobalKey();
    }
    if (_listDatas != null) {
      setState(() {});
    }
  }

  /// 分享弹窗
  _showShareBottomSheet() {
    showModalBottomSheet(
        context: context,
        builder: (BuildContext context) {
          return ShareBottomSheet(callback: (platform) async {
            ToastUtils.showLoading("准备中..");

            RenderRepaintBoundary boundary = _listDatas[currentPage]
                .globalKey
                .currentContext
                .findRenderObject();
            var image = await boundary.toImage(pixelRatio: 6.0);
            ByteData byteData =
                await image.toByteData(format: ImageByteFormat.png);
            Uint8List pngBytes = byteData.buffer.asUint8List();
            WeChatImage img = WeChatImage.binary(pngBytes);

            ToastUtils.dismissLoading();

            ShareSdkUtils.share(platform,
                title: "海报", image: img, callback: (success, msg) {});
          });
        });
  }

  @override
  void initState() {
    super.initState();
    pageController = new PageController(
      //用来配置PageView中默认显示的页面 从0开始
      initialPage: 0,
      //为true是保持加载的每个页面的状态
      keepPage: true,
    );

    pageController.addListener(() {
      //PageView滑动的距离
      double offset = pageController.offset;
      //当前显示的页面的索引
      double page = pageController.page;
      print("pageView 滑动的距离 $offset  索引 $page");
    });

    WidgetsBinding.instance.addPostFrameCallback((mag) {
      _getList();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: ThemeColors.colorWhite,
        appBar: _initAppBar(),
        body: Column(children: [
          Expanded(
              child: SingleChildScrollView(
                  physics: BouncingScrollPhysics(), child: _initBody()))
        ]));
  }

  /// 导航
  Widget _initAppBar() {
    return BaseAppBar(
      context,
      Text("我的二维码", style: FonStyle.navTextStyle()),
      actions: <Widget>[
        InkWell(
            onTap: () {
              LRouter.navigatorCtx(context).push(Routes.inviateBindingPage);
            },
            child: IntrinsicHeight(
                child: Container(
                    alignment: Alignment.center,
                    padding: EdgeInsets.only(
                        left: ScreenAdapter.width(15),
                        right: ScreenAdapter.width(30)),
                    child: Text("绑定邀请码",
                        style: TextStyle(color: ThemeColors.colorType6))))),
      ],
    );
  }

  /// 内容体
  Widget _initBody() {
    return Column(children: [
      Container(
          padding: EdgeInsets.symmetric(
              horizontal: ScreenAdapter.width(40),
              vertical: ScreenAdapter.height(40)),
          child: Stack(alignment: Alignment.center, children: [
            AspectRatio(
                aspectRatio: 650 / 1050,
                child: PageView.builder(
                    onPageChanged: (int index) {
                      currentPage = index;
                    },
                    itemCount: (_listDatas ?? []).length,
                    //值为true时 显示最后一个页面 然后从右向左开始滑动
                    reverse: false,
                    //滑动到页面底部无回弹效果
                    physics: BouncingScrollPhysics(),
                    //纵向滑动切换
                    scrollDirection: Axis.horizontal,
                    //页面控制器
                    controller: pageController,
                    itemBuilder: (BuildContext context, int index) {
                      return RepaintBoundary(
                          key: _listDatas[index].globalKey,
                          child: Stack(
                              fit: StackFit.expand,
                              alignment: Alignment.center,
                              children: [
                                MyNetImage(
                                    url: _listDatas[index].pic,
                                    radius: BorderRadius.circular(
                                        ScreenAdapter.width(10))),
                                Positioned(
                                    bottom: ScreenAdapter.height(178),
                                    child: QrImage(
                                      backgroundColor: ThemeColors.colorWhite,
                                      data: ApiPath.url_web_down,
                                      size: ScreenAdapter.width(240),
                                      padding: EdgeInsets.all(
                                          ScreenAdapter.width(25)),
                                    )),
                                Positioned(
                                    bottom: ScreenAdapter.height(115),
                                    child: Consumer(builder: (BuildContext ctx,
                                        UserProfileInfo profileInfo,
                                        Widget child) {
                                      inviteCode =
                                          profileInfo.userInfo.code ?? "邀请码";
                                      return Text(
                                          profileInfo.userInfo.code ?? "邀请码",
                                          style: TextStyle(
                                              color: ThemeColors.colorWhite,
                                              fontSize: ScreenAdapter.sp(40),
                                              fontWeight: FontWeight.bold));
                                    }))
                              ]));
                    })),
            GestureDetector(
                onTap: () {
                  if (currentPage > 0) {
                    pageController.animateToPage(
                      currentPage - 1,
                      curve: Curves.ease,
                      duration: Duration(milliseconds: 200),
                    );
                  } else {
                    ToastUtils.show("已经是第一页了");
                  }
                },
                child: Align(
                    alignment: Alignment.centerLeft,
                    child: Container(
                        width: ScreenAdapter.width(80),
                        height: ScreenAdapter.width(80),
                        child: Image.asset(
                            RPath.imgPath + "icon_arrow_left_white.png")))),
            GestureDetector(
                onTap: () {
                  if (currentPage < _listDatas.length - 1) {
                    pageController.animateToPage(
                      currentPage + 1,
                      curve: Curves.ease,
                      duration: Duration(milliseconds: 200),
                    );
                  } else {
                    ToastUtils.show("已经是最后一页了");
                  }
                },
                child: Align(
                    alignment: Alignment.centerRight,
                    child: Container(
                        width: ScreenAdapter.width(80),
                        height: ScreenAdapter.width(80),
                        // padding: EdgeInsets.all(ScreenAdapter.width(20)),
                        child: Image.asset(
                            RPath.imgPath + "icon_arrow_right_white.png"))))
          ])),
      Container(
          margin: EdgeInsets.symmetric(
              horizontal: ScreenAdapter.width(50),
              vertical: ScreenAdapter.height(30)),
          child:
              Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [
            Container(
              // margin: EdgeInsets.all(ScreenAdapter.width(30)),
              width: ScreenAdapter.width(300),
              height: ScreenAdapter.height(80),
              child: FlatButton(
                color: ThemeColors.colorType51,
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(ScreenAdapter.width(10)),
                ),
                child: Text(
                  "分享海报",
                  style: TextStyle(
                      color: ThemeColors.colorWhite,
                      fontSize: ScreenAdapter.sp(30)),
                ),
                onPressed: () {
                  _showShareBottomSheet();
                },
              ),
            ),
            Container(
              // margin: EdgeInsets.all(ScreenAdapter.width(30)),
              width: ScreenAdapter.width(300),
              height: ScreenAdapter.height(80),
              child: FlatButton(
                color: ThemeColors.colorType6,
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(ScreenAdapter.width(10)),
                ),
                child: Text(
                  "复制邀请码",
                  style: TextStyle(
                      color: ThemeColors.colorWhite,
                      fontSize: ScreenAdapter.sp(30)),
                ),
                onPressed: () {
                  Clipboard.setData(ClipboardData(text: inviteCode));
                  ToastUtils.show("邀请码已复制成功!");
                },
              ),
            )
          ]))
    ]);
  }

  /// 保存图片
  Future<void> saveImage(GlobalKey globalKey) async {
    RenderRepaintBoundary boundary =
        globalKey.currentContext.findRenderObject();
    var image = await boundary.toImage(pixelRatio: 6.0);
    ByteData byteData = await image.toByteData(format: ImageByteFormat.png);
    Uint8List pngBytes = byteData.buffer.asUint8List();
  }
}
